package kr.hkit.powerjava.chapter17;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class CmbPanel extends JPanel implements ActionListener {
	private static final long serialVersionUID = 1L;
	
	private JTextField tfAddItem;
	private JButton btnCmbAdd;
	private JComboBox<String> comboBox;
	private JTextField txtCmbSelected;

	public CmbPanel() {
		initialize();
	}
	
	private void initialize() {
		setLayout(new BorderLayout(0, 0));
		
		JPanel panelTop = new JPanel();
		tfAddItem = new JTextField();
		panelTop.add(tfAddItem);
		tfAddItem.setColumns(10);
		
		btnCmbAdd = new JButton("항목 추가");
		btnCmbAdd.addActionListener(this);
		panelTop.add(btnCmbAdd);
		
		add(panelTop, BorderLayout.NORTH);
		
		JPanel panelCenter = new JPanel();
		
		comboBox = new JComboBox<String>();
		comboBox.addActionListener(this);
		panelCenter.add(comboBox);
		
		add(panelCenter, BorderLayout.CENTER);
		
		JPanel panelBottom = new JPanel();
		JLabel lblNewLabel_2 = new JLabel("선택한 항목 :");
		panelBottom.add(lblNewLabel_2);
		
		txtCmbSelected = new JTextField(10);
		txtCmbSelected.setEditable(false);
		panelBottom.add(txtCmbSelected);
		
		add(panelBottom, BorderLayout.SOUTH);
	}


	public void actionPerformed(ActionEvent e) {
		if (e.getSource() == comboBox) {
			actionPerformedComboBox(e);
		}
		if (e.getSource() == btnCmbAdd) {
			actionPerformedBtnCmbAdd(e);
		}
	}
	
	protected void actionPerformedBtnCmbAdd(ActionEvent e) {
		comboBox.addItem(tfAddItem.getText());
		comboBox.updateUI();
	}
	
	protected void actionPerformedComboBox(ActionEvent e) {
		txtCmbSelected.setText((String) comboBox.getSelectedItem());
		tfAddItem.setText("");
		tfAddItem.requestFocus();
	}
}
